import React, {forwardRef, useEffect, useImperativeHandle, useState} from 'react';

interface ImageGalleryProps {
    images: { name: string, src: string }[],
    onData: (image: { name: string; src: string }) => void,
}

interface ImageGalleryState {
    // 第几页
    currentPage: number;
    // 每页显示的图片数
    imagesPerPage: number;
    // 总页数
    totalPages: number;
    // 当前页的图片数组下标
    currentIndex: number;
    // 当前图片名称
    currentImageName: string;
}

type ChildHandle = {
    gallerySelectNextImage: () => void;
};

// 定义状态类型
type ClickedState = Record<string, boolean>;

const ImageGallery = forwardRef<ChildHandle, ImageGalleryProps>((props, ref) => {

        const {images, onData} = props;

        // 图片选择状态
        const [isClicked, setIsClicked] = useState<ClickedState>({});

        const [imageGalleryState, setImageGalleryState] = useState<ImageGalleryState>({
            currentPage: 0,
            currentImageName: '',
            imagesPerPage: 100,
            totalPages: 0,
            currentIndex: 0,
        });

        useImperativeHandle(ref, () => ({
            gallerySelectNextImage: () => {
                // 选择下一张图片,具体操作。
                const newImages = images.filter((_, i) => i === imageGalleryState.currentIndex);
                let name: string = newImages[0].name;
                // 点击图片，记录选择状态，并触发回调函数
                setImageGalleryState({
                    ...imageGalleryState,
                    currentIndex: imageGalleryState.currentIndex + 1,
                    currentImageName: name
                })
                onData(newImages[0]);
                setIsClicked(() => {
                    return {[name]: true};
                })
            }
        }));


        if (images.length > 0) {

            const handleClick = (index: number) => {
                // 点击图片，记录选择状态，并触发回调函数
                const newImages = images.filter((_, i) => i === index);
                let name: string = newImages[0].name;
                setImageGalleryState({...imageGalleryState, currentIndex: index, currentImageName: name});
                onData(newImages[0]);
                // 记录选中状态。
                setIsClicked(() => {
                    return {[name]: true};
                })
            };


            imageGalleryState.totalPages = Math.ceil(images.length / imageGalleryState.imagesPerPage);

            const handleNextPage = () => {
                if (imageGalleryState.currentPage < imageGalleryState.totalPages - 1) {
                    setImageGalleryState({...imageGalleryState, currentPage: imageGalleryState.currentPage + 1});
                }
            };

            const handlePrevPage = () => {
                if (imageGalleryState.currentPage > 0) {
                    setImageGalleryState({...imageGalleryState, currentPage: imageGalleryState.currentPage - 1});
                }
            };

            const startIndex = imageGalleryState.currentPage * imageGalleryState.imagesPerPage;
            const currentImages = images.slice(startIndex, startIndex + imageGalleryState.imagesPerPage);

            // 图片样式
            const getImageStyle = (image: { name: string; src: string }) => {
                const isImageSelected = localStorage.getItem(`image_${image.name}`) === 'true';
                return {
                    maxWidth: '60px',
                    marginRight: '10px',
                    borderRadius: '8px',
                    border: isImageSelected ? '2px solid blue' : 'none',
                    cursor: 'pointer',
                    boxShadow: isClicked[image.name] ? '0 4px 8px rgba(0, 0, 255, 0.5)' : 'none', // 添加阴影效果
                };
            }

            return (
                <div>
                    <div
                        id="imageContainer"
                        style={{width: '1080px'}}
                        className="flex overflow-x-auto whitespace-nowrap mb-2">
                        {currentImages.map((image, index) => (
                            <img
                                key={index}
                                src={image.src}
                                alt={image.name}
                                style={getImageStyle(image)}
                                onClick={() => handleClick(startIndex + index)}
                            />
                        ))}
                    </div>
                    <div className="mt-1.5">
                        <button onClick={handlePrevPage} disabled={imageGalleryState.currentPage === 0}
                                className="btn btn-sm btn-primary">
                            上一页
                        </button>
                        <button onClick={handleNextPage}
                                disabled={imageGalleryState.currentPage === imageGalleryState.totalPages - 1}
                                className="btn btn-sm btn-primary">
                            下一页
                        </button>
                        <span className="ml-2">
                            第 {imageGalleryState.currentPage + 1} 页 / {imageGalleryState.totalPages} 页 ,当前选中的图片：{imageGalleryState.currentImageName}
                        </span>
                    </div>
                </div>


            );
        }
    })
;

export default ImageGallery;
